import CryptoJS from 'crypto-js';
import Md5 from 'crypto-js/md5.js';
import Vue from 'vue'

/**
 * 加密组装参数
 * @param {Object} Arr
 */
export function returnData(Arr) {
	var BArr = {};
	for (var i in Arr) {
		if (Arr[i] === true) {
			BArr[i] = 1;
		} else if (Arr[i] === false) {
			BArr[i] = 0;
		} else if (Arr[i] === null) {
			BArr[i] = '';
		} else {
			BArr[i] = Arr[i];
		}

	}

	var sig = getSign(Arr);
	var AesStr = aesEncrypt(BArr, sig);

	var JsonObj = {};
	// if(Arr.nodeenv === 'development') {
	// 	JsonObj = Arr;
	// }else{
		JsonObj['sig'] = sig;
		JsonObj['data'] = AesStr;
		JsonObj['token'] = Arr.token;
		JsonObj['ts'] = Arr.ts;
	// }
	return JsonObj;
}
/**
 * 签名
 */
export function getSign(obj) {
	let Arr = JSON.parse(JSON.stringify(obj));
	const appkey = Md5(Vue.prototype.$VUE_SYSTEM_ID + '_' + Vue.prototype.$VUE_SYSTEM_APPID).toString()
	const appsecret = Vue.prototype.$VUE_SYSTEM_APPSECRET;
	Arr.appkey = appkey;
	Arr.appsecret = appsecret;
	
	var newArr = sortList(Arr);
	var jsonStr = JSON.stringify(newArr);
	var md5Str = Md5(jsonStr + appsecret).toString();
	var str = Md5(md5Str + appkey).toString();
	return str;
}


/**
 * aes加密
 */
export function aesEncrypt(Arr, sign) {
	var key = sign.substring(0, 8) + sign.substring(16, 24);
	var iv = sign.substring(8, 16) + sign.substring(24, 32);
	var data = JSON.stringify(Arr);

	var encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
		iv: CryptoJS.enc.Utf8.parse(iv),
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	});
	return encrypted.toString();
}


/**
 * aes解密
 */
export function aesDecrypt(Str, sign) {
	var key = sign.substring(0, 8) + sign.substring(16, 24);
	var iv = sign.substring(8, 16) + sign.substring(24, 32);


	var decrypted = CryptoJS.AES.decrypt(decodeURIComponent(Str), CryptoJS.enc.Utf8.parse(key), {
		iv: CryptoJS.enc.Utf8.parse(iv),
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	});

	var plaintext = decrypted.toString(CryptoJS.enc.Utf8); //WordArray对象转utf8字符串

	if (plaintext.substring(0, 1) == '{') {
		return JSON.parse(plaintext.substring(0, (plaintext.lastIndexOf('}') + 1)));
	} else {
		return JSON.parse(plaintext.substring(0, (plaintext.lastIndexOf(']') + 1)));
	}
}

/**
 * 字典排序
 */
export function sortList(Arr) {
	var obj = JSON.parse(JSON.stringify(Arr));
	var indexArr = [];
	for (var i in obj) {
		if (obj[i] instanceof Object) {
			continue;
		} else if (obj[i] instanceof Array) {
			continue;
		} else {
			indexArr.push(i);
		}

	}
	indexArr.sort();
	var newArr = {};
	for (var j in indexArr) {
		for (var r in obj) {
			if (indexArr[j] == r) {
				newArr[indexArr[j]] = _urlencode(obj[indexArr[j]]);
			}
		}
	}
	return newArr;
}


/**
 * 
 * 特需字符转义
 */
export function _urlencode(str) {
	var newstr = encodeURIComponent(str);
	newstr = newstr.replace(/%20/g, '+');
	newstr = newstr.replace(/!/g, '%21');
	newstr = newstr.replace(/\(/g, '%28');
	newstr = newstr.replace(/\*/g, '%2A');
	newstr = newstr.replace(/\(/g, '%28');
	newstr = newstr.replace(/\)/g, '%29');
	newstr = newstr.replace(/'/g, '%27');
	newstr = newstr.replace(/~/g, '%7E');
	newstr = newstr.replace(/null/g, '');
	newstr = newstr.replace(/true/g, 1);
	newstr = newstr.replace(/false/g, 0); 
	return newstr;
}


export function cacheSet(name, data) {
	var _data = data || {};
	if (typeof _data !== 'object') {
		_data = {
			localStorageNames: data
		};
	}
	var _name = Md5(name).toString();
	// window.localStorage.setItem(_name, aesEncrypt(_data, _name));
	try {
		uni.setStorageSync(_name, aesEncrypt(_data, _name));
	} catch (e) {
		// error
		console.error(_name,e);
		return false;
	}
	
	return true;
}

export function cacheGet(name) {
	var _name = Md5(name).toString();
	// var value = window.localStorage.getItem(_name);
	var value = null;
	try {
		value = uni.getStorageSync(_name);
	} catch (e) {
		// error
		console.error(_name,e);
		return null;
	}
	
	if (!value) {
		return null;
	}
	var _json = aesDecrypt(value, _name);
	var str = _json.localStorageNames || null
	if (str != null) {
		return str;
	}
	if(JSON.stringify(_json) === '{}') {
		return null;
	}
	return _json;
}


export function cacheRemove(name) {
	var _name = Md5(name).toString();
	try {
		uni.removeStorageSync(_name);
	} catch (e) {
		// error
		return false;
	}
	return true;
}

export function cacheClear() {
	// window.localStorage.clear();
	try {
		uni.clearStorageSync();
	} catch (e) {
		// error
		return false;
	}
	return true;
}